<template>
    <view class="container">
        <NavBar title="物料领用" @back="goBack" />
        <scroll-view class="form-content" scroll-y>
            <!-- 表单内容 -->
            <view class="form-list">
                <view class="form-item">
                    <view class="form-label">
                        <text class="label-text">施工合同</text>
                    </view>
                    <view class="input-wrapper" @click="selectPeriod">
                        <!-- <text class="form-input" :class="{ placeholder: !form.contractName }">{{
                            form.contractName || '请选择'
                            }}</text> -->
							<uv-text v-show="!form.contractName" suffixIcon="arrow-down-fill" iconStyle="font-size: 8px" text="请选择"></uv-text>
							<text v-show="form.contractName">{{form.contractName}}</text>
                    </view>
                </view>
                <view class="form-item">
                    <view class="form-label">
                        <text class="label-text">计量周期</text>
                    </view>
                    <view class="input-wrapper" @click="selectCycle">
                        <!-- <text class="form-input" :class="{ placeholder: !form.cycleName }">{{
                            form.cycleName || '请选择'
                            }}</text> -->
							<uv-text v-show="!form.cycleName" suffixIcon="arrow-down-fill" iconStyle="font-size: 8px" text="请选择"></uv-text>
							<text v-show="form.cycleName">{{form.cycleName}}</text>
                    </view>
                </view>
                <view class="form-item">
                    <view class="form-label">
                        <text class="label-text">材料单价</text>
                    </view>
                    <view class="input-wrapper" @click="selectPrice">
                        <!-- <text class="form-input" :class="{ placeholder: !form.priceName }">{{
                            form.priceName || '请选择'
                            }}</text> -->
							<uv-text v-show="!form.priceName" suffixIcon="arrow-down-fill" iconStyle="font-size: 8px" text="请选择"></uv-text>
							<text v-show="form.priceName">{{form.priceName}}</text>
                    </view>
                </view>
                <view class="form-item">
                    <text class="form-label">领取单价</text>
                    <view class="input-wrapper">
                        <view class="input-with-unit" style="display: flex; align-items: center;">
                            <input class="form-input" @blur="blur('drawUnitPrice')" type="number" v-model="form.drawUnitPrice" placeholder="请输入"
                                style="flex:1;" />
                            <text class="unit-text" style="margin-left: 10rpx;">元</text>
                        </view>
                    </view>
                </view>
                <view class="form-item">
                    <text class="form-label">领取数量</text>
                    <view class="input-wrapper">
                        <input class="form-input" @blur="blur('drawNum')" type="number" v-model="form.drawNum" placeholder="请输入" />
                    </view>
                </view>
                <view class="form-item">
                    <text class="form-label">领用时间</text>
                    <view class="input-wrapper">
                        <uv-datetime-picker ref="datetimePicker" v-model="form.createTime" mode="datetime"
                            @confirm="confirm"></uv-datetime-picker>
                        <text @click="openClick">{{ (formatDateTime(form.createTime)) }}</text>
                    </view>
                </view>
                <view class="form-item">
                    <text class="form-label">备&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;注</text>
                    <view class="input-wrapper">
                        <input class="form-input" type="text" v-model="form.remark" placeholder="请输入" />
                    </view>
                </view>
                <view class="form-item file-item">
                    <text class="form-label">附&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;件</text>
                    <uv-upload :fileList="fileList" name="3" :maxCount="5" multiple :previewFullImage="true"
                        @afterRead="afterRead" @delete="deletePic" >
                        <view class="upload-icon">
                            <uv-icon name="plus"></uv-icon>
                        </view>
                    </uv-upload>
                </view>

                <view class="submit-button">
                    <button class="submit-btn" @click="submitForm">提交</button>
                </view>
            </view>
        </scroll-view>
    </view>
	<view v-if="isShowcontract" class="picker-containers">
	  <view class="picker-masks" @click="closeOutPickercontract()"></view>
	  <view class="picker-contents">
	    <view class="picker-headers">
	      <text class="picker-cancels" @click="closeOutPickercontract()">取消</text>
	      <text class="picker-titles">选择施工合同</text>
	      <text class="picker-confirms" @click="confirmOutsupplier()">确定</text>
	    </view>
	    <scroll-view scroll-y class="picker-lists">
	      <view  class="picker-items" v-for="(item, index) in contractList"  :key="index" 
	            :class="{ 'selecteds': form.contractId === item.id }"
	            @click="selectOutOptioncontract(item)">
	        <text>{{ item.name }}</text>
	      </view>
		  <view class="black-boxs">
		  	
		  </view>
	    </scroll-view>
		
	  </view>
	</view>
	<view v-if="isShowcycle" class="picker-containers">
	  <view class="picker-masks" @click="closeOutPickercycle()"></view>
	  <view class="picker-contents">
	    <view class="picker-headers">
	      <text class="picker-cancels" @click="closeOutPickercycle()">取消</text>
	      <text class="picker-titles">选择计量周期</text>
	      <text class="picker-confirms" @click="confirmOutsupplier()">确定</text>
	    </view>
	    <scroll-view scroll-y class="picker-lists">
	      <view  class="picker-items" v-for="(item, index) in cycleList"  :key="index" 
	            :class="{ 'selecteds': form.cycleId === item.id }"
	            @click="selectOutOptioncycle(item)">
	        <text>{{ item.name }}</text>
	      </view>
		  <view class="black-boxs">
		  	
		  </view>
	    </scroll-view>
		
	  </view>
	</view>
	<view v-if="isShowprice" class="picker-containers">
	  <view class="picker-masks" @click="closeOutPickerprice()"></view>
	  <view class="picker-contents">
	    <view class="picker-headers">
	      <text class="picker-cancels" @click="closeOutPickerprice()">取消</text>
	      <text class="picker-titles">选择材料单价</text>
	      <text class="picker-confirms" @click="confirmOutsupplier()">确定</text>
	    </view>
	    <scroll-view scroll-y class="picker-lists">
	      <view  class="picker-items" v-for="(item, index) in priceList"  :key="index" 
	            :class="{ 'selecteds': form.priceId === item.id }"
	            @click="selectOutOptionprice(item)">
	        <text>{{ item.name }}</text>
	      </view>
		  <view class="black-boxs">
		  	
		  </view>
	    </scroll-view>
		
	  </view>
	</view>
</template>

<script>
import NavBar from '@/components/NavBar/index.vue'
import { BASEURL } from '@/utils/request.js'
import {
    getContract,
    getCyclemanagement,
    getMaterialProjectSingle,
    getMaterialDraw
} from '@/utils/app.js'
export default {
    components: {
        NavBar
    },
    data() {
        return {
			isShowprice:false,
			isShowcycle:false,
			isShowcontract:false,
            contractList: [],
            cycleList: [],
            priceList: [],
            form: {
                createTime: Number(new Date())
            },
            gettime: '',
            queryParams: {},
            fileList: []
        }
    },
    onLoad(options) {
        this.queryParams = JSON.parse(decodeURIComponent(options.data));

        this.getContractData()

    },
    onPullDownRefresh() {
        this.getContractData()
    },
    methods: {
		blur(e){
			if(this.form[e] < 0){
				this.form[e] = ''
				uni.showToast({
				    title: '只能输入大于0的数字',
				    icon: 'none'
				});
			}
		},
        //施工合同列表
        getContractData() {
            let data = {
                projectId: this.queryParams.projectId,
            }
            getContract(data).then(res => {
                if (res.code == 200) {
                    //过滤parentId为0的
                    this.contractList = res.data.filter(item => item.parentId !== 0).map(item => ({
                        name: item.contractName,
                        id: item.id
                    }))
                }
            })
        },
        //计量周期列表
        getCyclemanagementData() {
            let data = {
                contractId: this.form.contractId
            }
            getCyclemanagement(data).then(res => {
                if (res && res.code == 200) {
                    this.cycleList = res.rows.map(item => ({
                        name: item.cycleName,
                        id: item.id
                    }))
                }
            })
        },
        //材料单价列表
        getMaterialProjectSingleData() {
            let data = {
                materialProjectId: this.queryParams.id,
                klyNum: 1
            }
            getMaterialProjectSingle(data).then(res => {
                if (res && res.code == 200) {
                    this.priceList = res.data.map(item => ({
                        name: `${item.unitPrice}元,${item.supplierName || ''}可领用量${item.klyNum}`,
                        id: item.id
                    }))
                }
            })
        },
        goBack() {
            uni.navigateBack();
        },
        //选择施工合同
        selectPeriod() {
			this.isShowcontract = true
            // const itemList = this.contractList.map(item => item.name)
            // uni.showActionSheet({
            //     itemList,
            //     success: (res) => {
            //         const selected = this.contractList[res.tapIndex];
            //         this.form.contractName = selected.name
            //         this.form.contractId = selected.id
            //         this.getCyclemanagementData()
            //     }
            // });

        },
		selectOutOptioncontract(item){
			this.form.contractName = item.name
			this.form.contractId = item.id
			this.getCyclemanagementData()
		},
		closeOutPickercontract(){
			this.form.contractName = ''
			this.form.contractId = ''
			this.isShowcontract = false
		},
        //选择计量周期
        selectCycle() {
			this.isShowcycle = true
            // const itemList = this.cycleList.map(item => item.name)
            // uni.showActionSheet({
            //     itemList,
            //     success: (res) => {
            //         const selected = this.cycleList[res.tapIndex];
            //         this.form.cycleName = selected.name
            //         this.form.cycleId = selected.id
            //         this.getMaterialProjectSingleData()
            //     }
            // });
        },
		selectOutOptioncycle(item){
			this.form.cycleName = item.name
			this.form.cycleId = item.id
			this.getMaterialProjectSingleData()
		},
		closeOutPickercycle(){
			this.form.cycleName = ''
			this.form.cycleId = ''
			this.isShowcycle = false
		},
        //选择材料单价
        selectPrice() {
			this.isShowprice = true
            // const itemList = this.priceList.map(item => item.name)
            // uni.showActionSheet({
            //     itemList,
            //     success: (res) => {
            //         const selected = this.priceList[res.tapIndex];
            //         this.form.priceName = selected.name
            //         this.form.priceId = selected.id
            //     }
            // });
        },
		selectOutOptionprice(item){
			this.form.priceName = item.name
			this.form.priceId = item.id
		},
		confirmOutsupplier(){
			this.isShowprice = false
			this.isShowcycle = false
			this.isShowcontract = false
			
		},
		closeOutPickerprice(){
			this.isShowprice = false
			this.form.priceName = ''
			this.form.priceId = ''
		},
        openClick() {
            if (this.$refs.datetimePicker) {
                this.$refs.datetimePicker.open();
            }
        },
        confirm(e) {
            this.form.createTime = e.value
        },
        formatDateTime(timestamp) {
            if (!timestamp) return '';
            const date = new Date(Number(timestamp));
            const Y = date.getFullYear();
            const M = (date.getMonth() + 1).toString().padStart(2, '0');
            const D = date.getDate().toString().padStart(2, '0');
            const h = date.getHours().toString().padStart(2, '0');
            const m = date.getMinutes().toString().padStart(2, '0');
            const s = date.getSeconds().toString().padStart(2, '0');
            return `${Y}-${M}-${D} ${h}:${m}:${s}`;
        },
        submitForm() {
            // 验证必填字段
            if (!this.form.contractId) {
                uni.showToast({
                    title: '请选择施工合同',
                    icon: 'none'
                });
                return
            }
            if (!this.form.cycleId) {
                uni.showToast({
                    title: '请选择计量周期',
                    icon: 'none'
                });
                return
            }
            if (!this.form.priceId) {
                uni.showToast({
                    title: '请选择材料单价',
                    icon: 'none'
                });
                return
            }
            if (!this.form.drawUnitPrice) {
                uni.showToast({
                    title: '请输入领取单价',
                    icon: 'none'
                });
                return
            }
            if (!this.form.drawNum) {
                uni.showToast({
                    title: '请输入领取数量',
                    icon: 'none'
                });
                return
            }
            if (!this.form.createTime) {
                uni.showToast({
                    title: '请输入领用时间',
                    icon: 'none'
                });
                return
            }
            let data = {
                ...this.form,
                createTime: this.formatDateTime(this.form.createTime),
                projectId: this.queryParams.projectId,
                materialProjectId: this.queryParams.id,
                projectSingleId: this.form.priceId,
                type: 1,
                annexe: this.form.annexe
            }
            // 本次领用数量不能超出单价对应的可领用量
            if (this.form.drawNum > this.form.priceName.split('可领用量')[1]) {
                uni.showToast({
                    title: '本次领用数量不能超出单价对应的可领用量',
                    icon: 'none'
                });
                return
            }
            getMaterialDraw(data).then(res => {
                if (res && res.code == 200) {
                    uni.showToast({
                        title: '提交成功',
                        icon: 'success'
                    });
                    setTimeout(() => {
                        uni.navigateBack({
                            delta: 1
                        })
                    }, 1000)
                }
            })
        },
        //删除附件
        deletePic(event) {
			// console.log(event.name,this.fileList,this[`fileList${event.name}`]);
            this.fileList.splice(event.index, 1)
        },
        //上传附件
        async afterRead(event) {
            // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
            let lists = [].concat(event.file)
            let fileListLen = this.fileList.length
            lists.map((item) => {
                this.fileList.push({
                    ...item,
                    status: 'uploading',
                    message: '上传中'
                })
            })
            for (let i = 0; i < lists.length; i++) {
                const result = await this.uploadFilePromise(lists[i].url)
                let item = this.fileList[fileListLen]
                this.fileList.splice(fileListLen, 1, Object.assign(item, {
                    status: 'success',
                    message: '',
                    url: result
                }))
                fileListLen++
            }
            //取出fileList中的url,拼接成字符串
            let urlList = this.fileList.map(item => item.url)
            this.form.annexe = urlList.join(',')
        },
        uploadFilePromise(url) {
            const token = uni.getStorageSync("token");
            return new Promise((resolve, reject) => {
                uni.uploadFile({
                    url: `${BASEURL}/common/upload`,
                    filePath: url,
                    name: 'file',
                    header: {
                        'Authorization': token,
                    },
                    success: (res) => {
                        // 这里的res.data其实是一个JSON字符串，需要先解析
                        try {
                            const data = JSON.parse(res.data)
                            // 判断data.annexUrl是否存在
                            if (data && data.annexUrl) {
                                resolve(data.annexUrl)
                            } else {
                                reject('上传返回数据中没有annexUrl字段')
                            }
                        } catch (e) {
                            reject('上传返回数据不是有效的JSON')
                        }
                    },
                    fail: (err) => {
                        reject(err)
                    }
                });
            })
        }
    }
}
</script>

<style lang="scss" scoped>
* {
    box-sizing: border-box;
}

.list {
    height: 1460rpx;
    padding: 0 30rpx;
    background-color: #fff;

    .list-item {
        display: flex;
        align-items: center;
        height: 112rpx;
        border-bottom: 1rpx solid #C9CDD4;

        .select {
            display: flex;
            align-items: center;
            padding-left: 28rpx;
        }

        .item-left {
            margin-right: 32rpx;
            width: 160rpx;
        }

        .item-right {
            flex: 1;
        }

        .input {
            border: 0;
        }
    }
}


.form-content {
    flex: 1;
    overflow: scroll;
}

.form-list {
    flex-direction: column;
}

.form-item {
    padding-left: 32rpx;
    height: 112rpx;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #E7E7E7;

    .form-label {
        width: 162rpx;
        margin-right: 32rpx;
    }

    .input-text {
        color: gray;
    }

    .input {
        border: 0;
    }
}

.form-label {
    width: 81px;
    height: 24px;
    font-size: 16px;
    color: rgba(0, 0, 0, 0.9);
    line-height: 24px;
}

.form-input {
    font-size: 16px;
    color: rgba(0, 0, 0, 0.85);
    border: none;
    outline: none;
    background: transparent;
}

.input-wrapper {
    flex: 1;
    margin-left: 16px;
    max-width: 450rpx;
    width: 450rpx;

    :deep(.uni-input-input) {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
    }
}

.placeholder {
    width: 100%;
    color: rgba(29, 33, 41, 0.65);
}

.submit-button {
    padding: 0 30px;
    margin-top: 84px;
    margin-bottom: 20px;
    width: 100%;
}

.submit-btn {
    height: 44px;
    border-radius: 22px;
    font-size: 16px;
    color: #4980FF;
    background-color: #F0F5FF;
    border-width: 0;
    justify-content: center;
    align-items: center;
    font-weight: 500;
    width: 100%;
}

:deep(.uv-upload__button) {
    width: 120rpx !important;
    height: 120rpx !important;
    margin-top: 30rpx;
}

.upload-icon {
    border: 1px solid #E6EAF3;
    width: 100rpx;
    height: 100rpx;
    display: flex;
    justify-content: center;
    align-items: center;
}

:deep(.uv-upload__wrap__preview) {
    width: 100rpx;
    height: 100rpx;
}

// :deep(.uv-upload__wrap) {
//     margin-top: 80rpx;
// }

.file-item {
    border-bottom: 0;
}

:deep(.uv-upload) {
    height: 20rpx;
}
/* 修改底部弹出层部分 */
		.picker-containers {
		  position: fixed;
		  left: 0;
		  right: 0;
		  bottom: 0;
		  top: 0;
		  z-index: 11000;
		}
		
		.picker-masks {
		  position: absolute;
		  top: 0;
		  left: 0;
		  right: 0;
		  bottom: 0;
		  background-color: rgba(0, 0, 0, 0.4);
		}
		
		.picker-contents {
		  position: absolute;
		  left: 0;
		  right: 0;
		  bottom: 0;
		  height: 500rpx;
		  background-color: #FFFFFF;
		  border-top-left-radius: 16px;
		  border-top-right-radius: 16px;
		}
		
		.picker-headers {
		  display: flex;
		  height: 53px;
		  flex-direction: row;
		  justify-content: space-between;
		  align-items: center;
		  padding: 0 16px;
		  border-bottom-width: 1px;
		  border-bottom-color: #EEF2F9;
		  margin-bottom: 30rpx;
		}
		
		.picker-titles {
		  font-size: 16px;
		  color: #1D2129;
		  font-weight: 400;
		}
		
		.picker-cancels, .picker-confirms {
		  font-size: 16px;
		}
		
		.picker-cancels {
		  color: #86909C;
		}
		
		.picker-confirms {
		  color: #165DFF;
		}
		
		.picker-lists {
		  padding: 24rpx 0;
		  max-height: 350rpx;
		  /* overflow: scroll; */
		}
		
		.picker-items {
			display: flex;
		  height: 44px;
		  flex-direction: row;
		  justify-content: center;
		  align-items: center;
		  padding: 0 16px;
		  overflow: hidden;
		  white-space: nowrap;
		  text-overflow: ellipsis;
		}
		.selecteds{
			background-color: #E8F3FF;
		}
		.black-boxs{
			height: 50rpx;
		}
		.picker-items text {
		  font-size: 16px;
		  color: #1D2129;
		}
</style>